package com.free4inno.knowledgems.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.free4inno.knowledgems.constants.GroupConstants;
import com.free4inno.knowledgems.constants.TemplateConstants;
import com.free4inno.knowledgems.constants.UserConstants;
import com.free4inno.knowledgems.dao.SignupInfoDAO;
import com.free4inno.knowledgems.dao.TemplateDAO;
import com.free4inno.knowledgems.dao.UserDAO;
import com.free4inno.knowledgems.dao.UserGroupDAO;
import com.free4inno.knowledgems.domain.*;
import com.free4inno.knowledgems.service.CleanResourceService;
import com.free4inno.knowledgems.service.UserService;
import com.free4inno.knowledgems.utils.ImageUtils;
import com.free4inno.knowledgems.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * UserInfoController.
 */
@Slf4j
@Controller
@RequestMapping("/template")
public class TemplateInfoController {

    @Autowired
    private UserDAO userDao;

    @Autowired
    private TemplateDAO templateDAO;


    @Autowired
    private ImageUtils imageUtils;

    @RequestMapping("/templateInfo")
    public String getTemplateInfo(Map param, HttpSession session) {
        log.info(this.getClass().getName() + "----in----" + "获取用户信息(userInfo)" + "----" + session.getAttribute(UserConstants.USER_ID));
        if (session.getAttribute(GroupConstants.ROLE_ID).equals(1) || session.getAttribute(GroupConstants.ROLE_ID).equals(2)) {
            List<User> userInfos = userDao.findAll();
            int userNum = userDao.findAll().size();
            param.put(UserConstants.USER_NUM, userNum);
            param.put(UserConstants.USER_INFOS, userInfos);
            log.info(this.getClass().getName() + "----out----" + "用户有权限，返回用户信息页面" + "----" + session.getAttribute(UserConstants.USER_ID));
            return "template/templateInfo";
        } else {
            log.info(this.getClass().getName() + "----out----" + "用户无权限" + "----" + session.getAttribute(UserConstants.USER_ID));
            return "redirect:/";
        }
    }

    @ResponseBody
    @PostMapping("/deleteTemplate")
    public String deleteTemplate(@RequestParam("templateId") Integer templateId, HttpSession session) {
        log.info(this.getClass().getName()+"----in----"+"删除模板(deleteTemplate)"+"----"+session.getAttribute(UserConstants.USER_ID));
        templateDAO.deleteById(templateId);
        String result = "ok";
        log.info(this.getClass().getName()+"----out----"+"删除成功，返回ok"+"----"+session.getAttribute(UserConstants.USER_ID));
        return result;
    }

    @RequestMapping("/templateContent")
    public String getTemplateContent(@RequestParam("templateId") int templateId, Map param, HttpSession session) {
        log.info(this.getClass().getName()+"----in----" + "获取模板信息(templateContent)" + "----" + session.getAttribute(UserConstants.USER_ID));
        Template templateInfo = templateDAO.findById(templateId).orElse(new Template());

        System.out.println("templateInfo: "+templateInfo.getTemplateName()+" "+templateInfo.getTemplateCode());

        param.put(TemplateConstants.TEMPLATE_INFO, templateInfo);


        log.info(this.getClass().getName()+"----out----" + "跳转到模板信息页" + "----" + session.getAttribute(UserConstants.USER_ID));
        return "template/templateContents";
    }



    @RequestMapping("/editTemplate")
    public String editTemplate(@RequestParam("id") Integer id, HttpSession session, Map param) {
        log.info(this.getClass().getName() + "----in----" + "编辑模板" + "----" + session.getAttribute(UserConstants.USER_ID));

        Template template = templateDAO.findById(id).get();
        System.out.print("初始数据："+template.getTemplateName()+"  "+template.getTemplateCode());
        template.setTemplateName(StringUtils.inputStringFormat(template.getTemplateName()));
        template.setTemplateCode(StringUtils.inputStringFormat(template.getTemplateCode()));
        System.out.print("处理后数据："+template.getTemplateName()+"  "+template.getTemplateCode());



        param.put("template", template);
        log.info(this.getClass().getName() + "----out----" + "跳转到编辑资源页面" + "----" + session.getAttribute(UserConstants.USER_ID));
        return "template/editTemplate";
    }


    @RequestMapping("/editSaveTemplate")
    @ResponseBody
    public Map<String, Object> editSaveTemplate(@RequestParam("id") Integer id,
                                        @RequestParam("name") String name,
                                        @RequestParam("text") String text,
                                        HttpSession session,
                                        HttpServletRequest request) throws Exception {
        log.info(this.getClass().getName() + "----in----" + "保存编辑模板(editSaveTemplate)" + "----" + session.getAttribute(UserConstants.USER_ID));
        Map<String, Object> jsonObject = new HashMap<>();
        if (id == null) {
            log.info(this.getClass().getName() + "----out----" + "保存编辑模板失败，模板id参数为null" + "----" + session.getAttribute(UserConstants.USER_ID));
            return jsonObject;
        }
        Template template = templateDAO.findById(id).get();
        if (name.equals("") || text.equals("")) {
            jsonObject.put("msg", "必填项未填写完整");
            log.info(this.getClass().getName() + "----out----" + "保存编辑模板失败(必填项未填写完整)" + "----" + session.getAttribute(UserConstants.USER_ID));
            return jsonObject;
        }
        text = imageUtils.DownloadExternalImage(text, session); //调用ImageUtils下载外链图片的方法
        //System.out.print(imageSrc);
        template.setTemplateName(name);
        template.setTemplateCode(text);
        template.setSetTime(new Timestamp(new Date().getTime()));
        templateDAO.saveAndFlush(template);


        jsonObject.put("msg", "SUCCESS");
        log.info(this.getClass().getName() + "----out----" + "保存编辑模板成功，返回成功json" + "----" + session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }


    @RequestMapping("newTemplate")
    @ResponseBody
    public Map<String, Object> newRTemplate(@RequestParam("name") String name,
                                           @RequestParam("text") String text,
                                           HttpSession session,
                                           HttpServletRequest request) throws Exception {
        log.info(this.getClass().getName() + "----in----" + "保存新模板(newTemplate)" + "----" + session.getAttribute(UserConstants.USER_ID));
        Map<String, Object> jsonObject = new HashMap<>();
        if (name.equals("") || text.equals("")) {
            jsonObject.put("msg", "必填项未填写完整");
            log.info(this.getClass().getName() + "----out----" + "保存新建模板失败(必填项未填写完整)" + "----" + session.getAttribute(UserConstants.USER_ID));
            return jsonObject;
        }
        text = imageUtils.DownloadExternalImage(text, session); //调用ImageUtils下载外链图片的方法
        Template template = new Template();
        template.setTemplateName(name);
        template.setTemplateCode(text);
        template.setCreateTime(new Timestamp(new Date().getTime()));
        template.setSetTime(new Timestamp(new Date().getTime()));

        templateDAO.save(template);

        jsonObject.put("msg", "SUCCESS");
        jsonObject.put("templateId", template.getId());
        log.info(this.getClass().getName() + "----out----" + "保存新建模板成功，返回模板id "+template.getId() + "----" + session.getAttribute(UserConstants.USER_ID));
        return jsonObject;
    }


    @RequestMapping("/templateManagement")
    public String getAllTemplates(Map param,
                               @RequestParam("page") int currentPage,
                               @RequestParam("search") String searchKey,
                               HttpSession session) {
        log.info(this.getClass().getName()+"----in----" + "模板管理页面(templateManagement)" + "----" + session.getAttribute(UserConstants.USER_ID));

        int maxItems = 10;
        int pageNum = 0;
        int searchedTemplateNum = 0;
        List<Template> templateInfos = new ArrayList<>();

        // judge search
        if (searchKey.isEmpty()){
            // no search and query all through page
            Sort sort = Sort.by(Sort.Direction.ASC, "id");
            Pageable pageable = PageRequest.of(currentPage - 1, maxItems, sort);
            Page<Template> templatePage = templateDAO.findAll(pageable);

            // get content and page number
            pageNum = templatePage.getTotalPages();
            templateInfos = templatePage.getContent();
            searchedTemplateNum = templateDAO.findAll().size();
            //searchedGroupNum = groupPage.getNumberOfElements();

        } else {
            // get all
            templateInfos = templateDAO.findAll();

            // do search
            List<Template> beforeSearchTemplateList = templateInfos;
            List<Template> searchedTemplateList = new ArrayList<>();
            for (Template template : beforeSearchTemplateList) {
                Pattern p = Pattern.compile(searchKey, Pattern.CASE_INSENSITIVE);
                Matcher m1 = p.matcher(template.getTemplateName());

                if (m1.find()) {
                    searchedTemplateList.add(template);
                }
            }
            // manual page
            pageNum = searchedTemplateList.size() / maxItems;
            int remainNum = searchedTemplateList.size() % maxItems;
            if (remainNum > 0) {
                pageNum++;
            }
            List<Template> pagedTemplateList;
            if (currentPage * maxItems < searchedTemplateList.size()) {
                pagedTemplateList = searchedTemplateList.subList((currentPage - 1) * maxItems, currentPage * maxItems);
            } else {
                pagedTemplateList = searchedTemplateList.subList((currentPage - 1) * maxItems, searchedTemplateList.size());
            }

            templateInfos = pagedTemplateList;
            searchedTemplateNum = searchedTemplateList.size();
        }



        // group list
        param.put(TemplateConstants.TEMPLATE_LIST, templateInfos);
        // page info
        param.put(TemplateConstants.MAX_PAGES, pageNum);
        param.put(TemplateConstants.CURRENT_PAGE, currentPage);
        // search info
        param.put(TemplateConstants.SEARCH, searchKey);
        param.put(TemplateConstants.SEARCHED_TEMPLATENUM, searchedTemplateNum);

        log.info(this.getClass().getName()+"----out----" + "跳转到模板管理页面" + "----" + session.getAttribute(UserConstants.USER_ID));
        return "template/_templateList";
    }


    static class UserNotFoundException extends RuntimeException {
        UserNotFoundException(Integer id, HttpSession session) {
            super(UserConstants.NO_USERINFO + id);
            log.error(this.getClass().getName()+"----"+"find user info by id"+"----failure----"+"Not found user info " + id +"----"+session.getAttribute(UserConstants.USER_ID));
        }
    }
}
